<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>Java实现哔哩哔哩视频下载 | 小苑の博客</title><meta name="author" content="coderyh"><meta name="copyright" content="coderyh"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="具体流程 通过BV号获取网页源码 请求的网页源码使用GZIP进行了压缩，需要解压   从网页源码中提取下载链接 音频链接 视频链接   开始下载 普通方式下载 多线程方式下载    注意：  视频可以直接修改为mp4格式 音频需要进行处理  普通方式下载视频（哔哩哔哩）主方法12345678910111213public class Main &amp;#123;    public static voi">
<meta property="og:type" content="article">
<meta property="og:title" content="Java实现哔哩哔哩视频下载">
<meta property="og:url" content="http://localhost:4000/blog/20240103230517/index.html">
<meta property="og:site_name" content="小苑の博客">
<meta property="og:description" content="具体流程 通过BV号获取网页源码 请求的网页源码使用GZIP进行了压缩，需要解压   从网页源码中提取下载链接 音频链接 视频链接   开始下载 普通方式下载 多线程方式下载    注意：  视频可以直接修改为mp4格式 音频需要进行处理  普通方式下载视频（哔哩哔哩）主方法12345678910111213public class Main &amp;#123;    public static voi">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://localhost:8080/image?1704294317000">
<meta property="article:published_time" content="2024-01-03T15:05:17.000Z">
<meta property="article:modified_time" content="2024-01-03T15:05:59.595Z">
<meta property="article:author" content="coderyh">
<meta property="article:tag" content="Java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://localhost:8080/image?1704294317000"><link rel="shortcut icon" href="/blog/img/favicon.png"><link rel="canonical" href="http://localhost:4000/blog/20240103230517/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/blog/',
  algolia: undefined,
  localSearch: {"path":"/blog/./search.xml","preload":false,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: {"limitDay":365,"position":"top","messagePrev":"It has been","messageNext":"days since the last update, the content of the article may be outdated."},
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: true,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Java实现哔哩哔哩视频下载',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2024-01-03 23:05:59'
}</script><script>(win=>{
      win.saveToLocal = {
        set: (key, value, ttl) => {
          if (ttl === 0) return
          const now = Date.now()
          const expiry = now + ttl * 86400000
          const item = {
            value,
            expiry
          }
          localStorage.setItem(key, JSON.stringify(item))
        },
      
        get: key => {
          const itemStr = localStorage.getItem(key)
      
          if (!itemStr) {
            return undefined
          }
          const item = JSON.parse(itemStr)
          const now = Date.now()
      
          if (now > item.expiry) {
            localStorage.removeItem(key)
            return undefined
          }
          return item.value
        }
      }
    
      win.getScript = (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        script.onerror = reject
        script.onload = script.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          script.onload = script.onreadystatechange = null
          resolve()
        }

        Object.keys(attr).forEach(key => {
          script.setAttribute(key, attr[key])
        })

        document.head.appendChild(script)
      })
    
      win.getCSS = (url, id = false) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onerror = reject
        link.onload = link.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          link.onload = link.onreadystatechange = null
          resolve()
        }
        document.head.appendChild(link)
      })
    
      win.activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
        if (t === 'dark') activateDarkMode()
        else if (t === 'light') activateLightMode()
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
      const detectApple = () => {
        if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
          document.documentElement.classList.add('apple')
        }
      }
      detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>(()=>{
  const $loadingBox = document.getElementById('loading-box')
  const $body = document.body
  const preloader = {
    endLoading: () => {
      $body.style.overflow = ''
      $loadingBox.classList.add('loaded')
    },
    initLoading: () => {
      $body.style.overflow = 'hidden'
      $loadingBox.classList.remove('loaded')
    }
  }

  preloader.initLoading()
  window.addEventListener('load',() => { preloader.endLoading() })

  if (false) {
    document.addEventListener('pjax:send', () => { preloader.initLoading() })
    document.addEventListener('pjax:complete', () => { preloader.endLoading() })
  }
})()</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/blog/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">25</div></a><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">16</div></a><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">8</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 导航</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/navigation/work/"><i class="fa-fw fas fa-coffee"></i><span> 工作</span></a></li><li><a class="site-page child" href="/blog/navigation/moyu/"><i class="fa-fw fas fa-th-list"></i><span> 摸鱼</span></a></li><li><a class="site-page child" href="/blog/navigation/code/"><i class="fa-fw fas fa-code"></i><span> 开发</span></a></li><li><a class="site-page child" href="/blog/navigation/design/"><i class="fa-fw fas fa-pencil-alt"></i><span> 设计</span></a></li><li><a class="site-page child" href="/blog/navigation/resource/"><i class="fa-fw fas fa-book"></i><span> 资源</span></a></li><li><a class="site-page child" href="/blog/navigation/tool/"><i class="fa-fw fas fa-wrench"></i><span> 工具</span></a></li><li><a class="site-page child" href="/blog/navigation/project/"><i class="fa-fw fas fa-project-diagram"></i><span> 项目</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-desktop"></i><span> 软件</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/software/usual/"><i class="fa-fw fas fa-desktop"></i><span> 常用</span></a></li><li><a class="site-page child" href="/blog/software/code/"><i class="fa-fw fas fa-code"></i><span> 开发</span></a></li><li><a class="site-page child" href="/blog/software/open/"><i class="fa-fw fas fa-code-branch"></i><span> 开源</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-compass"></i><span> 目录</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li><li><a class="site-page child" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/blog/gallery/"><i class="fa-fw fas fa-images"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-user"></i><span> 设置</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/pro/"><i class="fa-fw fas fa-user"></i><span> 页面管理</span></a></li><li><a class="site-page child" href="/blog/admin/"><i class="fa-fw fas fa-user"></i><span> 后台管理</span></a></li><li><a class="site-page child" href="/blog/bridge/"><i class="fa-fw fas fa-cog"></i><span> 配置管理</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('http://localhost:8080/image?1704294317000')"><nav id="nav"><span id="blog-info"><a href="/blog/" title="小苑の博客"><span class="site-name">小苑の博客</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 导航</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/navigation/work/"><i class="fa-fw fas fa-coffee"></i><span> 工作</span></a></li><li><a class="site-page child" href="/blog/navigation/moyu/"><i class="fa-fw fas fa-th-list"></i><span> 摸鱼</span></a></li><li><a class="site-page child" href="/blog/navigation/code/"><i class="fa-fw fas fa-code"></i><span> 开发</span></a></li><li><a class="site-page child" href="/blog/navigation/design/"><i class="fa-fw fas fa-pencil-alt"></i><span> 设计</span></a></li><li><a class="site-page child" href="/blog/navigation/resource/"><i class="fa-fw fas fa-book"></i><span> 资源</span></a></li><li><a class="site-page child" href="/blog/navigation/tool/"><i class="fa-fw fas fa-wrench"></i><span> 工具</span></a></li><li><a class="site-page child" href="/blog/navigation/project/"><i class="fa-fw fas fa-project-diagram"></i><span> 项目</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-desktop"></i><span> 软件</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/software/usual/"><i class="fa-fw fas fa-desktop"></i><span> 常用</span></a></li><li><a class="site-page child" href="/blog/software/code/"><i class="fa-fw fas fa-code"></i><span> 开发</span></a></li><li><a class="site-page child" href="/blog/software/open/"><i class="fa-fw fas fa-code-branch"></i><span> 开源</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-compass"></i><span> 目录</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li><li><a class="site-page child" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/blog/gallery/"><i class="fa-fw fas fa-images"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-user"></i><span> 设置</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/pro/"><i class="fa-fw fas fa-user"></i><span> 页面管理</span></a></li><li><a class="site-page child" href="/blog/admin/"><i class="fa-fw fas fa-user"></i><span> 后台管理</span></a></li><li><a class="site-page child" href="/blog/bridge/"><i class="fa-fw fas fa-cog"></i><span> 配置管理</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Java实现哔哩哔哩视频下载</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2024-01-03T15:05:17.000Z" title="发表于 2024-01-03 23:05:17">2024-01-03</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-01-03T15:05:59.595Z" title="更新于 2024-01-03 23:05:59">2024-01-03</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E7%88%AC%E8%99%AB%E7%B3%BB%E5%88%97/">爬虫系列</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.7k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>8分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Java实现哔哩哔哩视频下载"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="具体流程"><a href="#具体流程" class="headerlink" title="具体流程"></a>具体流程</h2><ol>
<li>通过BV号获取网页源码<ul>
<li>请求的网页源码使用GZIP进行了压缩，需要解压</li>
</ul>
</li>
<li>从网页源码中提取下载链接<ul>
<li>音频链接</li>
<li>视频链接</li>
</ul>
</li>
<li>开始下载<ul>
<li>普通方式下载</li>
<li>多线程方式下载</li>
</ul>
</li>
</ol>
<p>注意：</p>
<ul>
<li>视频可以直接修改为mp4格式</li>
<li>音频需要进行处理</li>
</ul>
<h2 id="普通方式下载视频（哔哩哔哩）"><a href="#普通方式下载视频（哔哩哔哩）" class="headerlink" title="普通方式下载视频（哔哩哔哩）"></a>普通方式下载视频（哔哩哔哩）</h2><h3 id="主方法"><a href="#主方法" class="headerlink" title="主方法"></a>主方法</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Main</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;请输入视频url&quot;</span>);</span><br><span class="line">        <span class="type">Scanner</span> <span class="variable">scanner</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Scanner</span>(System.in);</span><br><span class="line"></span><br><span class="line">        <span class="type">String</span> <span class="variable">videoUrl</span> <span class="operator">=</span> scanner.next();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//开始下载</span></span><br><span class="line">        <span class="type">DownLoad</span> <span class="variable">downLoad</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DownLoad</span>(videoUrl);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="从BV页面提取下载链接"><a href="#从BV页面提取下载链接" class="headerlink" title="从BV页面提取下载链接"></a>从BV页面提取下载链接</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> bilibili;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.jsoup.Jsoup;</span><br><span class="line"><span class="keyword">import</span> org.jsoup.nodes.Document;</span><br><span class="line"><span class="keyword">import</span> org.jsoup.nodes.Element;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.*;</span><br><span class="line"><span class="keyword">import</span> java.net.HttpURLConnection;</span><br><span class="line"><span class="keyword">import</span> java.net.MalformedURLException;</span><br><span class="line"><span class="keyword">import</span> java.net.URL;</span><br><span class="line"><span class="keyword">import</span> java.util.regex.Pattern;</span><br><span class="line"><span class="keyword">import</span> java.util.zip.GZIPInputStream;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">DownLoad</span> &#123;</span><br><span class="line">    <span class="keyword">static</span> String baseUrl;</span><br><span class="line"></span><br><span class="line">    DownLoad(String baseUrl)&#123;</span><br><span class="line">        <span class="built_in">this</span>.baseUrl = baseUrl;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//通过BV号</span></span><br><span class="line">        <span class="type">URL</span> <span class="variable">url</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">        <span class="type">HttpURLConnection</span> <span class="variable">httpURLConnection</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">        <span class="type">InputStream</span> <span class="variable">inputStream</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">        <span class="type">OutputStream</span> <span class="variable">outputStream</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;why&quot;</span>+baseUrl);</span><br><span class="line">                url = <span class="keyword">new</span> <span class="title class_">URL</span>(baseUrl);</span><br><span class="line">                httpURLConnection = (HttpURLConnection) url.openConnection();</span><br><span class="line">                httpURLConnection.setRequestMethod(<span class="string">&quot;GET&quot;</span>);</span><br><span class="line">                httpURLConnection.setRequestProperty(<span class="string">&quot;user-agent&quot;</span>,<span class="string">&quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36&quot;</span>);</span><br><span class="line"></span><br><span class="line">                inputStream = httpURLConnection.getInputStream();</span><br><span class="line"></span><br><span class="line">                outputStream = <span class="keyword">new</span> <span class="title class_">FileOutputStream</span>(<span class="string">&quot;./temp.gz&quot;</span>);</span><br><span class="line"></span><br><span class="line">                <span class="type">int</span> <span class="variable">len</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">                <span class="type">byte</span>[] bytes = <span class="keyword">new</span> <span class="title class_">byte</span>[<span class="number">1024</span>*<span class="number">1024</span>];<span class="comment">//1M</span></span><br><span class="line">                <span class="keyword">while</span> ((len = inputStream.read(bytes))!=-<span class="number">1</span>)&#123;</span><br><span class="line">                    outputStream.write(bytes,<span class="number">0</span>,len);</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="comment">//解压</span></span><br><span class="line">                <span class="type">GZIPInputStream</span> <span class="variable">gzipInputStream</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">GZIPInputStream</span>(<span class="keyword">new</span> <span class="title class_">FileInputStream</span>(<span class="string">&quot;./temp.gz&quot;</span>));</span><br><span class="line">                <span class="type">InputStreamReader</span> <span class="variable">inputStreamReader</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">InputStreamReader</span>(gzipInputStream,<span class="string">&quot;UTF-8&quot;</span>);</span><br><span class="line">                <span class="type">int</span> <span class="variable">lem</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">                <span class="type">String</span> <span class="variable">html</span> <span class="operator">=</span> <span class="string">&quot;&quot;</span>;</span><br><span class="line">                <span class="keyword">while</span> ((lem = inputStreamReader.read())!=-<span class="number">1</span>)&#123;</span><br><span class="line"><span class="comment">//                    System.out.print((char) lem);</span></span><br><span class="line">                    html+=((<span class="type">char</span>) lem);</span><br><span class="line">                &#125;</span><br><span class="line">                System.out.println(<span class="string">&quot;主页代码&quot;</span>);</span><br><span class="line">                System.out.println(<span class="string">&quot;====================&quot;</span>);</span><br><span class="line"><span class="comment">//                System.out.println(html);</span></span><br><span class="line"></span><br><span class="line">                <span class="comment">//Jsoup</span></span><br><span class="line">                <span class="type">Document</span> <span class="variable">doc</span> <span class="operator">=</span> Jsoup.parse(html);</span><br><span class="line">                <span class="comment">//获取视频名称</span></span><br><span class="line">                System.out.println(doc.getElementsByTag(<span class="string">&quot;title&quot;</span>).text());</span><br><span class="line">                <span class="comment">//获取视频信息</span></span><br><span class="line">                <span class="type">String</span> <span class="variable">allScript</span> <span class="operator">=</span> doc.getElementsByTag(<span class="string">&quot;script&quot;</span>).toString();</span><br><span class="line">                <span class="type">String</span> <span class="variable">playInfo</span> <span class="operator">=</span> allScript.substring(allScript.indexOf(<span class="string">&quot;window.__playinfo__=&quot;</span>)+<span class="number">20</span>,allScript.indexOf(<span class="string">&quot;&lt;script&gt;window.__INITIAL_STATE__=&#123;&quot;</span>));</span><br><span class="line">                System.out.println(playInfo);</span><br><span class="line">                <span class="comment">//m4s视频地址</span></span><br><span class="line">                <span class="type">String</span> <span class="variable">m4s</span> <span class="operator">=</span> playInfo.substring(playInfo.indexOf(<span class="string">&quot;baseUrl&quot;</span>)+<span class="number">10</span>,playInfo.indexOf(<span class="string">&quot;base_url&quot;</span>)-<span class="number">3</span>);</span><br><span class="line">                System.out.println(m4s);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">            &#125; <span class="keyword">catch</span> (MalformedURLException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="工具类"><a href="#工具类" class="headerlink" title="工具类"></a>工具类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> bilibili;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.io.InputStream;</span><br><span class="line"><span class="keyword">import</span> java.io.InputStreamReader;</span><br><span class="line"><span class="keyword">import</span> java.net.HttpURLConnection;</span><br><span class="line"><span class="keyword">import</span> java.net.MalformedURLException;</span><br><span class="line"><span class="keyword">import</span> java.net.URL;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">DownLoadUtil</span> &#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 获取网页源码</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> base 网页url</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span>  网页源码</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> IOException</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">static</span> String <span class="title function_">getHtml</span><span class="params">(String base)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">        <span class="type">URL</span> <span class="variable">url</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">URL</span>(base);</span><br><span class="line"></span><br><span class="line">        <span class="type">HttpURLConnection</span> <span class="variable">httpURLConnection</span> <span class="operator">=</span> (HttpURLConnection) url.openConnection();</span><br><span class="line">        <span class="comment">//设置请求参数</span></span><br><span class="line">        httpURLConnection.setRequestMethod(<span class="string">&quot;OPTIONS&quot;</span>);</span><br><span class="line">        httpURLConnection.setRequestProperty(<span class="string">&quot;Refer&quot;</span>,<span class="string">&quot;https://www.bilibili.com/video/BV1Vt4y1i7xW/&quot;</span>);</span><br><span class="line">        httpURLConnection.setRequestProperty(<span class="string">&quot;User-Agent&quot;</span>,<span class="string">&quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">InputStream</span> <span class="variable">inputStream</span> <span class="operator">=</span> httpURLConnection.getInputStream();</span><br><span class="line"></span><br><span class="line">        <span class="type">InputStreamReader</span> <span class="variable">inputStreamReader</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">InputStreamReader</span>(inputStream,<span class="string">&quot;UTF-8&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">int</span> <span class="variable">len</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">        <span class="type">String</span> <span class="variable">html</span> <span class="operator">=</span> <span class="string">&quot;&quot;</span>;</span><br><span class="line">        <span class="keyword">while</span> ((len = inputStreamReader.read())!=-<span class="number">1</span>)&#123;</span><br><span class="line">            html+=(<span class="type">char</span>)len;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> html;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="下载类"><a href="#下载类" class="headerlink" title="下载类"></a>下载类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> bilibili;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.*;</span><br><span class="line"><span class="keyword">import</span> java.net.HttpURLConnection;</span><br><span class="line"><span class="keyword">import</span> java.net.URL;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">Download</span><span class="params">()</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">        <span class="comment">//开始时间</span></span><br><span class="line">        <span class="type">long</span> <span class="variable">startTime</span> <span class="operator">=</span> System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">        <span class="type">URL</span> <span class="variable">url</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">URL</span>(<span class="string">&quot;https://upos-sz-mirrorcoso1.bilivideo.com/upgcxcode/47/23/242302347/242302347-1-30080.m4s?e=ig8euxZM2rNcNbdlhoNvNC8BqJIzNbfqXBvEqxTEto8BTrNvN0GvT90W5JZMkX_YN0MvXg8gNEV4NC8xNEV4N03eN0B5tZlqNxTEto8BTrNvNeZVuJ10Kj_g2UB02J0mN0B5tZlqNCNEto8BTrNvNC7MTX502C8f2jmMQJ6mqF2fka1mqx6gqj0eN0B599M=&amp;uipk=5&amp;nbs=1&amp;deadline=1636803872&amp;gen=playurlv2&amp;os=coso1bv&amp;oi=1992794824&amp;trid=83a5918306bd420f8e9a67cbf05cecc5u&amp;platform=pc&amp;upsig=77b819cd149bd044dd27b4641d21edab&amp;uparams=e,uipk,nbs,deadline,gen,os,oi,trid,platform&amp;mid=584774873&amp;bvc=vod&amp;nettype=0&amp;orderid=1,3&amp;agrr=1&amp;bw=99446&amp;logo=40000000&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">HttpURLConnection</span> <span class="variable">httpURLConnection</span> <span class="operator">=</span> (HttpURLConnection) url.openConnection();</span><br><span class="line"></span><br><span class="line">        httpURLConnection.setRequestMethod(<span class="string">&quot;GET&quot;</span>);</span><br><span class="line">        httpURLConnection.setRequestProperty(<span class="string">&quot;Referer&quot;</span>,<span class="string">&quot;https://www.bilibili.com/video/BV1Qy4y1k7Ys/&quot;</span>);</span><br><span class="line">        httpURLConnection.setRequestProperty(<span class="string">&quot;User-Agent&quot;</span>,<span class="string">&quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">InputStream</span> <span class="variable">inputStream</span> <span class="operator">=</span> httpURLConnection.getInputStream();</span><br><span class="line">        <span class="type">OutputStream</span> <span class="variable">outputStream</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">FileOutputStream</span>(<span class="string">&quot;./compare1.m4s&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">int</span> <span class="variable">len</span> <span class="operator">=</span> <span class="number">0</span> ;</span><br><span class="line">        <span class="keyword">while</span> ((len = inputStream.read())!=-<span class="number">1</span>)&#123;</span><br><span class="line">            outputStream.write(len);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">&quot;success&quot;</span>);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h2 id="多线程下载视频（哔哩哔哩）"><a href="#多线程下载视频（哔哩哔哩）" class="headerlink" title="多线程下载视频（哔哩哔哩）"></a>多线程下载视频（哔哩哔哩）</h2><p>具体思路：</p>
<ol>
<li><p>文件分块</p>
<p>文件分块大小（blockSIze）&#x3D;文件大小&#x2F;线程数</p>
</li>
<li><p>确定每个线程所需要下载的文件的起始位置和结束位置</p>
<p>假设为每个线程分别编号为0，1，2，3；第一个线程负责下载位置是0*blockSize + （0+1X）</p>
</li>
<li><p>设置请求头</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">connection.setRequestProperty(&quot;Range&quot;,&quot;bytes=&quot;+start+&quot;-&quot;+&quot;end&quot;)</span><br></pre></td></tr></table></figure></li>
</ol>
<p>多线程下载视频源码</p>
<p>测试类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Example</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> MalformedURLException &#123;</span><br><span class="line">        <span class="type">String</span> <span class="variable">downPath</span> <span class="operator">=</span> <span class="string">&quot;保存本地的位置&quot;</span>;</span><br><span class="line">        <span class="type">String</span> <span class="variable">fileUrl</span> <span class="operator">=</span> <span class="string">&quot;视频URL地址&quot;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//多线程下载视频</span></span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">DownloadLoader</span>(fileUrl,downPath).downRedio();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>视频下载类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> bilibili;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.*;</span><br><span class="line"><span class="keyword">import</span> java.net.HttpURLConnection;</span><br><span class="line"><span class="keyword">import</span> java.net.MalformedURLException;</span><br><span class="line"><span class="keyword">import</span> java.net.URL;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.CountDownLatch;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">DownloadLoader</span>&#123;</span><br><span class="line">    <span class="comment">//目标地址</span></span><br><span class="line">    <span class="keyword">private</span> URL url;</span><br><span class="line">    <span class="comment">//本地文件</span></span><br><span class="line">    <span class="keyword">private</span> File file;</span><br><span class="line">    <span class="comment">//线程数</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">THREAD_AMOUNT</span> <span class="operator">=</span> <span class="number">10</span>;</span><br><span class="line">    <span class="comment">//文件目标路径</span></span><br><span class="line">    <span class="keyword">private</span> String address;</span><br><span class="line">    <span class="comment">//文件本地路径</span></span><br><span class="line">    <span class="keyword">private</span> String downloadPath;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//构造方法：初始化信息</span></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">DownloadLoader</span><span class="params">(String address,String downloadPath)</span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="built_in">this</span>.address = address;</span><br><span class="line">            <span class="built_in">this</span>.downloadPath = downloadPath;</span><br><span class="line">            url = <span class="keyword">new</span> <span class="title class_">URL</span>(address);</span><br><span class="line">            file = <span class="keyword">new</span> <span class="title class_">File</span>(downloadPath);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (MalformedURLException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//向外提供的下载方法</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">downRedio</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//防止SSL错误(我也不知道这是什么，先跟着别人这么写吧)</span></span><br><span class="line">            System.setProperty(<span class="string">&quot;https.protocols&quot;</span>,<span class="string">&quot;TLSv1,TLSv1.1,TLSv1.2,SSLv3&quot;</span>);</span><br><span class="line">            <span class="type">CountDownLatch</span> <span class="variable">countDownLatch</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">CountDownLatch</span>(THREAD_AMOUNT);</span><br><span class="line">            <span class="comment">//调用本类的下载方法</span></span><br><span class="line">            <span class="keyword">new</span> <span class="title class_">DownloadLoader</span>(address,downloadPath).download(countDownLatch);</span><br><span class="line">            countDownLatch.await();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException | InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//具体下载方法的实现</span></span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">download</span><span class="params">(CountDownLatch countDownLatch)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">        <span class="type">HttpURLConnection</span> <span class="variable">connection</span> <span class="operator">=</span> (HttpURLConnection) url.openConnection();</span><br><span class="line">        <span class="comment">//设置超时时间</span></span><br><span class="line">        connection.setConnectTimeout(<span class="number">5000</span>);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//=========================设置哔哩哔哩请求头信息</span></span><br><span class="line">        connection.setRequestMethod(<span class="string">&quot;GET&quot;</span>);</span><br><span class="line">        connection.setRequestProperty(<span class="string">&quot;Referer&quot;</span>,<span class="string">&quot;https://www.bilibili.com/video/BV1Qy4y1k7Ys/&quot;</span>);</span><br><span class="line">        connection.setRequestProperty(<span class="string">&quot;User-Agent&quot;</span>,<span class="string">&quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36&quot;</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">//获取文件总长度</span></span><br><span class="line">        <span class="type">int</span> <span class="variable">totalLength</span> <span class="operator">=</span> connection.getContentLength();</span><br><span class="line">        <span class="comment">//==================</span></span><br><span class="line">        System.out.println(<span class="string">&quot;文件总长度&quot;</span>+totalLength);</span><br><span class="line">        <span class="comment">//计算每个线程需要下载的长度(100+10-1)/10=109/10=10</span></span><br><span class="line">        <span class="type">int</span> <span class="variable">threadLength</span> <span class="operator">=</span> (totalLength + THREAD_AMOUNT -<span class="number">1</span>)/THREAD_AMOUNT;</span><br><span class="line">        <span class="comment">//在本地创建一个和服务端大小相同的文件</span></span><br><span class="line">        <span class="type">RandomAccessFile</span> <span class="variable">randomAccessFile</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">RandomAccessFile</span>(file,<span class="string">&quot;rws&quot;</span>);</span><br><span class="line">        <span class="comment">//设置文件的总大小</span></span><br><span class="line">        randomAccessFile.setLength(totalLength);</span><br><span class="line">        randomAccessFile.close();</span><br><span class="line">        <span class="comment">//开启线程，每个线程下载一部分数据到本地文件中</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; THREAD_AMOUNT; i++) &#123;</span><br><span class="line">            <span class="keyword">new</span>  <span class="title class_">DownloadThread</span>(i,countDownLatch,threadLength,url,file).start();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>多线程下载类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">DownloadThread</span> <span class="keyword">extends</span> <span class="title class_">Thread</span>&#123;</span><br><span class="line">    <span class="comment">//当前线程数</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> count;</span><br><span class="line">    <span class="comment">//用来计算线程是否已经结束</span></span><br><span class="line">    <span class="keyword">private</span> CountDownLatch countDownLatch;</span><br><span class="line">    <span class="comment">//计算每个线程下载多少</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> threadLength;</span><br><span class="line">    <span class="comment">//路径url</span></span><br><span class="line">    <span class="keyword">private</span> URL url;</span><br><span class="line">    <span class="comment">//文件</span></span><br><span class="line">    <span class="keyword">private</span> File file;</span><br><span class="line"></span><br><span class="line">    DownloadThread(<span class="type">int</span> count,CountDownLatch countDownLatch,<span class="type">int</span> threadLength,URL url,File file)&#123;</span><br><span class="line">        <span class="built_in">this</span>.count = count;</span><br><span class="line">        <span class="built_in">this</span>.countDownLatch = countDownLatch;</span><br><span class="line">        <span class="built_in">this</span>.threadLength = threadLength;</span><br><span class="line">        <span class="built_in">this</span>.url = url;</span><br><span class="line">        <span class="built_in">this</span>.file = file;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">//起始位置</span></span><br><span class="line">        <span class="type">int</span> <span class="variable">start</span> <span class="operator">=</span> count*threadLength;</span><br><span class="line">        <span class="comment">//结束位置</span></span><br><span class="line">        <span class="type">int</span> <span class="variable">end</span> <span class="operator">=</span> count*threadLength + threadLength - <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="type">HttpURLConnection</span> <span class="variable">connection</span> <span class="operator">=</span>(HttpURLConnection) url.openConnection();</span><br><span class="line">            connection.setConnectTimeout(<span class="number">5000</span>);</span><br><span class="line">            <span class="comment">//设置当前线程的下载范围</span></span><br><span class="line">            connection.setRequestProperty(<span class="string">&quot;Range&quot;</span>,<span class="string">&quot;bytes=&quot;</span> + start + <span class="string">&quot;-&quot;</span> + end);</span><br><span class="line">            </span><br><span class="line">            <span class="comment">//=====================设置哔哩哔哩请求头信息</span></span><br><span class="line">            connection.setRequestMethod(<span class="string">&quot;GET&quot;</span>);</span><br><span class="line">            connection.setRequestProperty(<span class="string">&quot;Referer&quot;</span>,<span class="string">&quot;https://www.bilibili.com/video/BV1Qy4y1k7Ys/&quot;</span>);</span><br><span class="line">            connection.setRequestProperty(<span class="string">&quot;User-Agent&quot;</span>,<span class="string">&quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36&quot;</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">            <span class="type">InputStream</span> <span class="variable">inputStream</span> <span class="operator">=</span> connection.getInputStream();</span><br><span class="line">            <span class="type">RandomAccessFile</span> <span class="variable">raf</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">RandomAccessFile</span>(file,<span class="string">&quot;rws&quot;</span>);</span><br><span class="line">            <span class="comment">//设置保存数据的值(指针移到下载位置)</span></span><br><span class="line">            raf.seek(start);</span><br><span class="line">            <span class="type">byte</span>[] buffer = <span class="keyword">new</span> <span class="title class_">byte</span>[<span class="number">1024</span>];</span><br><span class="line">            <span class="type">int</span> len;</span><br><span class="line">            <span class="keyword">while</span> ((len = inputStream.read(buffer))!=-<span class="number">1</span>)&#123;</span><br><span class="line">                raf.write(buffer,<span class="number">0</span>,len);</span><br><span class="line">            &#125;</span><br><span class="line">            raf.close();</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;<span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="comment">//每次执行完，线程数-1</span></span><br><span class="line">            countDownLatch.countDown();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="涉及的知识点"><a href="#涉及的知识点" class="headerlink" title="涉及的知识点"></a>涉及的知识点</h2><h3 id="countDownLatch"><a href="#countDownLatch" class="headerlink" title="countDownLatch"></a>countDownLatch</h3><p>这是一个与线程相关的多线程同步工具类，用来实现多线程的同步</p>
<h3 id="SSL错误"><a href="#SSL错误" class="headerlink" title="SSL错误"></a>SSL错误</h3></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="http://localhost:4000/blog">coderyh</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="http://localhost:4000/blog/20240103230517/">http://localhost:4000/blog/20240103230517/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://localhost:4000/blog" target="_blank">小苑の博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/Java/">Java</a></div><div class="post_share"><div class="social-share" data-image="http://localhost:8080/image?1704294317000" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/20240103230802/" title="Linux系列"><img class="cover" src="http://localhost:8080/image?1704294482000" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Linux系列</div></div></a></div><div class="next-post pull-right"><a href="/blog/20240103230333/" title="键盘上F1-F12的作用"><img class="cover" src="http://localhost:8080/image?1704294213000" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">键盘上F1-F12的作用</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%B7%E4%BD%93%E6%B5%81%E7%A8%8B"><span class="toc-number">1.</span> <span class="toc-text">具体流程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%99%AE%E9%80%9A%E6%96%B9%E5%BC%8F%E4%B8%8B%E8%BD%BD%E8%A7%86%E9%A2%91%EF%BC%88%E5%93%94%E5%93%A9%E5%93%94%E5%93%A9%EF%BC%89"><span class="toc-number">2.</span> <span class="toc-text">普通方式下载视频（哔哩哔哩）</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BB%E6%96%B9%E6%B3%95"><span class="toc-number">2.1.</span> <span class="toc-text">主方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%8EBV%E9%A1%B5%E9%9D%A2%E6%8F%90%E5%8F%96%E4%B8%8B%E8%BD%BD%E9%93%BE%E6%8E%A5"><span class="toc-number">2.2.</span> <span class="toc-text">从BV页面提取下载链接</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B7%A5%E5%85%B7%E7%B1%BB"><span class="toc-number">2.3.</span> <span class="toc-text">工具类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%8B%E8%BD%BD%E7%B1%BB"><span class="toc-number">2.4.</span> <span class="toc-text">下载类</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A4%9A%E7%BA%BF%E7%A8%8B%E4%B8%8B%E8%BD%BD%E8%A7%86%E9%A2%91%EF%BC%88%E5%93%94%E5%93%A9%E5%93%94%E5%93%A9%EF%BC%89"><span class="toc-number">3.</span> <span class="toc-text">多线程下载视频（哔哩哔哩）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B6%89%E5%8F%8A%E7%9A%84%E7%9F%A5%E8%AF%86%E7%82%B9"><span class="toc-number">4.</span> <span class="toc-text">涉及的知识点</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#countDownLatch"><span class="toc-number">4.1.</span> <span class="toc-text">countDownLatch</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#SSL%E9%94%99%E8%AF%AF"><span class="toc-number">4.2.</span> <span class="toc-text">SSL错误</span></a></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2023 - 2024 By coderyh</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">页脚自定义文本</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="/blog/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.jsdelivr.net/npm/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><div class="js-pjax"><script>(() => {
  const $mermaid = document.querySelectorAll('#article-container .mermaid-wrap')
  if ($mermaid.length === 0) return
  const runMermaid = () => {
    window.loadMermaid = true
    const theme = document.documentElement.getAttribute('data-theme') === 'dark' ? 'dark' : 'default'

    Array.from($mermaid).forEach((item, index) => {
      const mermaidSrc = item.firstElementChild
      const mermaidThemeConfig = '%%{init:{ \'theme\':\'' + theme + '\'}}%%\n'
      const mermaidID = 'mermaid-' + index
      const mermaidDefinition = mermaidThemeConfig + mermaidSrc.textContent

      const renderFn = mermaid.render(mermaidID, mermaidDefinition)

      const renderV10 = () => {
        renderFn.then(({svg}) => {
          mermaidSrc.insertAdjacentHTML('afterend', svg)
        })
      }

      const renderV9 = svg => {
        mermaidSrc.insertAdjacentHTML('afterend', svg)
      }

      typeof renderFn === 'string' ? renderV9(renderFn) : renderV10()
    })
  }

  const loadMermaid = () => {
    window.loadMermaid ? runMermaid() : getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(runMermaid)
  }

  btf.addGlobalFn('themeChange', runMermaid, 'mermaid')

  window.pjax ? loadMermaid() : document.addEventListener('DOMContentLoaded', loadMermaid)
})()</script><script>(() => {
  const abcjsInit = () => {
    const abcjsFn = () => {
      document.querySelectorAll(".abc-music-sheet").forEach(ele => {
        ABCJS.renderAbc(ele, ele.innerHTML, {responsive: 'resize'})
      })
    }
    
    typeof ABCJS === 'object' ? abcjsFn()
      : getScript('https://cdn.jsdelivr.net/npm/abcjs/dist/abcjs-basic-min.min.js').then(abcjsFn)
  }

  window.pjax ? abcjsInit() : window.addEventListener('load', abcjsInit)
})()</script></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="false"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/blog/js/search/local-search.js"></script></div></div></body></html>